package com.leyou.auth.task;

import com.leyou.auth.config.JwtProperties;
import com.leyou.common.auth.entity.AppInfo;
import com.leyou.auth.mapper.ApplicationInfoMapper;
import com.leyou.common.auth.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @package com.leyou.auth.task
 * @description: 定时刷新服务token
 * @author: 许超越
 * @date 2019/7/9 20:08
 * @version: V1.0
 */
@Slf4j
@Component
public class PrivilegeTokenHolder {

    @Autowired
    private JwtProperties prop;

    @Autowired
    private ApplicationInfoMapper appMapper;

    private String token;

    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;

    @Scheduled(fixedDelay = TOKEN_REFRESH_INTERVAL)
    public void loadToken() {
        try {
            //查询服务列表
            List<Long> targetIdList = appMapper.queryTargetIdList(prop.getAppTokenProperties().getId());
            //封装载荷
            AppInfo appInfo = new AppInfo();
            appInfo.setId(prop.getAppTokenProperties().getId());
            appInfo.setServiceName(prop.getAppTokenProperties().getSecret());
            appInfo.setTargetList(targetIdList);
            //生成token
            this.token = JwtUtils.generateTokenExpireInMinutes(appInfo, prop.getPrivateKey(), prop.getAppTokenProperties().getExpire());
            log.info("【授权中心】定时获取token成功");
        } catch (Exception e) {
            log.info("【授权中心】定时获取token失败");
        }
    }

    public String getToken() {
        return token;
    }
}
